package com.zc.study.java开发实战1200例.第十章_网络应用基础.网络地址解析_10_1.多线程下载资源;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 线程实现下载功能
 */
public class DownMultiThread implements Runnable {
    private String sUrl ="";//网络资源地址
    private File desFile;//需要写入的目标文件对象
    private long startPos;//写入的开始位置
   private long endPos;//写入的结束的位置

    public DownMultiThread(String sUrl, File desFile, long startPos, long endPos) {
        this.sUrl = sUrl;
        this.desFile = desFile;
        this.startPos = startPos;
        this.endPos = endPos;
    }

    @Override
    public void run() {
        try {
            RandomAccessFile out = new RandomAccessFile(desFile,"rw");//创建可读写的流对象
            out.seek(startPos);//指定读写的开始标记
            URL url = new URL(sUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            InputStream in = conn.getInputStream();//获得网络资源的输入流对象
            BufferedInputStream bin = new BufferedInputStream(in);//创建输入缓冲流对象
            byte[] buff =new byte[2048];//创建字节数组
            int len = -1;
            len = bin.read(buff);
            while(len!=-1){
                out.write(buff,0,len);
                len=bin.read(buff);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
